var _=require('lodash');

var initialState={
	lists:[],
    carts:[],
    curpage:'1',
    userId:''
}

function product(state=initialState,action){
    switch(action.type){
        case "SAVEUSERID"://获取产品列表
            return Object.assign({},state,{userId:action.data});
        case "GETLISTS"://获取产品列表
            state.curpage=action.data.page;
            return Object.assign({},state,{lists:action.data});
        case "GETCARTS":
            return Object.assign({},state,{carts:action.data});
        case "ADDTOCART"://添加产品与增加数量（+1）
            state.carts = _.uniqWith(state.carts,_.isEqual);
            let posAdd =_.findIndex(state.carts,{'_id':action.data._id});
            let num1 =null;
            if(posAdd === -1){
                action.data.quantity=1;
                num1 = 1;
            }else{
                state.carts[posAdd].quantity = state.carts[posAdd].quantity +1;
                num1 = state.carts[posAdd].quantity;
                action.data.quantity=num1;
            };
            fetchToUpdate(state.userId,action.data._id,num1);

            return {
                ...state,
                carts:[
                    ...state.carts,
                    action.data
                ]
            }
        case "REDUCENUM"://减少数量1
            state.carts = _.uniqWith(state.carts,_.isEqual);
            let posRed =_.findIndex(state.carts,{'_id':action.data._id});
            let num2 =null;
            if(state.carts[posRed].quantity>1){
                state.carts[posRed].quantity=state.carts[posRed].quantity -1;
                num2 = state.carts[posRed].quantity;
            }else{
                num2=1;
                console.info('当前数量1，如不需要，请点击删除按钮')
            };
            fetchToUpdate(state.userId,action.data._id,num2);
		return {
			...state,
			carts:[
				...state.carts,
				action.data
			]
        }
        
        case "DELETE"://删除
            _.pull(state.carts, action.data)
            fetch('http://localhost:3000/carts/remove', {
                method: 'delete',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId:state.userId,
                    productId:action.data._id,
                })
            })
            .then(res=>{
                console.log(res)
            })
		return {
			...state,
			carts:[
				...state.carts
			]
		}

        default:
            return state;
    }
}

function fetchToUpdate(userId,productId,num){
    fetch('http://localhost:3000/carts/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            userId:userId,
            productId:productId,
            productNum:num
        })
    })
    .then(res=>{
        console.log(res)
    })
}



export default product;